import { createSlice } from "@reduxjs/toolkit"

const tabSlice = createSlice({
  name: "tab",
  initialState: {
    isCollapse: true,
    tabList: [
      {
        path: "/",
        name: "home",
        label: "首页"
      }
    ],
    currentMenu: {}
  },
  reducers: {
    collapseMenu: state => {
      state.isCollapse = !state.isCollapse
    },
    selectMenuList: (state, { payload: value }) => {
      if (value.name !== "home") {
        state.currentMenu = value
        const index = state.tabList.findIndex(item => item.name === value.name)
        if (index === -1) {
          state.tabList.push(value)
        }
      } else if (value.name === "home" && state.tabList.length === 1) {
        state.currentMenu = {}
      }
    },
    colseTab: (state, { payload: value }) => {
      let index = state.tabList.findIndex(item => item.name === value.name)
      state.tabList.splice(index, 1)
    },
    setCurrentMenu: (state, { payload: value }) => {
      if (value.name === "home") {
        state.currentMenu = {}
      } else {
        state.currentMenu = value
      }
    }
  }
})

export const { collapseMenu, selectMenuList, colseTab, setCurrentMenu } = tabSlice.actions
export default tabSlice.reducer